//
//  BN_DynamicClassData.m
//  BabyNow
//
//  Created by 刘泽琛 on 14-3-29.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//

#import "BN_DynamicClassData.h"
#import "AppDelegate.h"

@implementation BN_DynamicClassData {
    
    NSArray *files_;
    NSInteger replTime_;
    NSIndexPath *currentIndexPath;
    
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    BN_DynamicCell *currentCell;

}


/**
 *  从网络获得的数据
 */
- (void)loadNetData {
    
    /**
     *  解决block 循环问题 添加 blockSelf_
     */
    __block BN_DynamicClassData *blockSelf_ = self;
    _dynamicHelper.queryClassListCompleteHandler = ^(id result,NSString *errorMsg){
        // update by jason yan 2014-05-30
        if (errorMsg) {
            [[NSNotificationCenter defaultCenter]postNotificationName:KDYNAMIC_HINTMESSAGE object:errorMsg];
            blockSelf_.listReload(YES);
        }
        if(result){
            [blockSelf_ useNetDate:result];
            blockSelf_.listReload(YES);
        }
    };
    // 测试加载第一页
    [_dynamicHelper refreshClassList];
    
}

// 得到下一页数据
- (void)loadNextNetData {
    __block BN_DynamicClassData *blockSelf_ = self;
    _dynamicHelper.queryClassListCompleteHandler = ^(id result,NSString *errorMsg){
        
        if (errorMsg) {
            [[NSNotificationCenter defaultCenter]postNotificationName:KDYNAMIC_HINTMESSAGE object:errorMsg];
        }
        // update by jason yan 2014-05-30
        if(result){
            [blockSelf_ useNetDate:result];
        }
    };
    // 测试加载第二页班级动态
    [_dynamicHelper fetchNextPageForClass];
}

// 获得数据 重新加载Tableview
- (void)useNetDate:(id)info {
    self.netArray = (NSMutableArray *)info;
    [self.classTableView reloadData];
}

/**
 *  计算cell高度
 */
- (float)calcCellHeight:(NSIndexPath *)indexPath {
    NSString *fileFlgStr = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"fileFlg"]];
    float height = 0.0;
    
    // notiSubj 高度
    NSString *notiSubj = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"postSubj"]];
    UIFont * contLabelfont = [UIFont systemFontOfSize:APP_CONTENT_FONT_SIZE];
    CGSize contLabelsize = CGSizeMake(296,10000);
    NSDictionary * contLabeldic = [NSDictionary dictionaryWithObjectsAndKeys:contLabelfont,NSFontAttributeName,nil];
    // 2014-06-16 没有上传文本，“说点什么吧”不显示
    CGSize contLabelActualsize = [self getTextSize:contLabelsize disFont:contLabelfont contentStr:notiSubj contextDic:contLabeldic];
    files_ = self.netArray[indexPath.row][@"files"];
    replTime_ = [self.netArray[indexPath.row][@"replTime"]integerValue];
    
    // 评论View高度
    NSInteger replCount = 0;
    if (replTime_ >= 3) {
        replCount = 3*15+10;
    }
    if (replTime_ == 2) {
        replCount = 2*15+5;
    }
    if (replTime_ == 1) {
        replCount = 15;
    }
    if (replTime_ == 0) {
        replCount = -15;
    }
    
    // 判断视频||图片
    // 视频
    if ([fileFlgStr isEqualToString:@"1"]) {
        height = 475+replCount+(contLabelActualsize.height-15);
    }else {
        if (files_.count == 1) {
            
            height = 475+replCount+(contLabelActualsize.height-15);
        }
        if (files_.count == 2) {
            height = 315+replCount+(contLabelActualsize.height-10);
        }
        if (files_.count == 3) {
            height = 315-(160-106)+replCount+(contLabelActualsize.height-15);
        }
        if (files_.count == 4) {
            height = 315+160+replCount+(contLabelActualsize.height-15);
        }
        if (files_.count == 5 || files_.count == 6) {
            height = 315+(160-106)+replCount+(contLabelActualsize.height-15);
        }
        
        if (files_.count > 6) {
            height = 315+(160-106)+106+replCount+(contLabelActualsize.height-15);
        }
    }
    
    NSLog(@"第%ld条cell,行高%f",indexPath.row,height);
    return height;
}

- (id)init {
    if (self = [super init]) {
        self.classTableView = [[UITableView alloc]init];
        if (IOS7) {
            self.classTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, FULLSCREEN_HEIGHT);
            self.classTableView.contentInset = UIEdgeInsetsMake(64+CLASSPARENTVIEWHEIGHT, 0, HEIGHT_TAB_BAR, 0);
            self.classTableView.scrollIndicatorInsets = UIEdgeInsetsMake(64+CLASSPARENTVIEWHEIGHT, 0, HEIGHT_TAB_BAR, 0);
        }else {
            self.classTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-CLASSPARENTVIEWHEIGHT);
            self.classTableView.contentInset = UIEdgeInsetsMake(CLASSPARENTVIEWHEIGHT, 0, HEIGHT_TAB_BAR+10, 0);
            self.classTableView.scrollIndicatorInsets = UIEdgeInsetsMake(CLASSPARENTVIEWHEIGHT, 0, HEIGHT_TAB_BAR+10, 0);
        }
        self.classTableView.delegate = self;
        self.classTableView.dataSource = self;
        [self setExtraCellLineHidden:self.classTableView];
        
        // 下拉刷新
        MJRefreshHeaderView *header = [MJRefreshHeaderView header];
        header.scrollView = self.classTableView;
        header.delegate = self;
        
        // 自动刷新
        _header = header;
        
        // 上拉加载更多
        MJRefreshFooterView *footer = [MJRefreshFooterView footer];
        footer.scrollView = self.classTableView;
        footer.delegate = self;
        _footer = footer;
        
        // 初始化动态Helper
        if (!_dynamicHelper) {
            _dynamicHelper = [[BN_DynamicHelper alloc]init];
        }
        [self loadNetData];
        
        NSUserDefaults *userD = [NSUserDefaults standardUserDefaults];
        [userD setInteger:0 forKey:USERDEFAULTS_CLASSPARENT];
        [userD synchronize];
        
        // 添加触发Tableview Reload通知
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reloadDataForTableView) name:KRELOADCLASSTABLEVIEW object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(autoRefreshClassTableView:) name:KCLASSAUTOREFRESH object:nil];
        
        if ([self.classTableView respondsToSelector:@selector(setSeparatorInset:)]) {
            [self.classTableView setSeparatorInset:UIEdgeInsetsZero];
        }
        
        // @"KREMOVE_VIDEOPLAYER"
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(removeVideoView:) name:@"KREMOVE_VIDEOPLAYER" object:nil];
    }
    return self;
}

#pragma mark
#pragma mark 刷新
- (void)upLoadFinished:(MJRefreshBaseView *)refreshView {
    // 列表开始加载，开始数据请求
    [self loadNextNetData];
    
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 列表开始刷新，开始数据请求
    [self loadNetData];

    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    if (_header == refreshView) {
        [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:0.0];
    }else {
        [self performSelector:@selector(upLoadFinished:) withObject:refreshView afterDelay:0.0];
    }
}

- (void)refreshViewEndRefreshing:(MJRefreshBaseView *)refreshView
{
}

- (void)refreshView:(MJRefreshBaseView *)refreshView stateChange:(MJRefreshState)state
{
    switch (state) {
        case MJRefreshStateNormal:
            break;
            
        case MJRefreshStatePulling:
            break;
            
        case MJRefreshStateRefreshing:
            break;
        default:
            break;
    }
}

- (void)reloadClassList {
    [self.classTableView reloadData];
}

#pragma mark
#pragma mark UIScrollViewDelegae

float currentContentOffset;
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    currentContentOffset = scrollView.contentOffset.y;
    
    // 微视视频效果
    AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
    UIWindow *window = appDelegate.window;
    BN_DynamicCell *cell = (BN_DynamicCell *)[self.classTableView cellForRowAtIndexPath:currentIndexPath];
    for (cell in self.classTableView.visibleCells) {
        CGRect f = [self.classTableView convertRect:cell.frame toView:window];
        if (CGRectIntersectsRect(f, self.lineLabel.frame)) {
            currentCell = cell;
            
        }else{
            
            if (cell.moviePlayer.playbackState == MPMoviePlaybackStatePlaying) {
                [cell removeMovieView];
            }
            for (UIView *view in cell.displayImageView.subviews) {
                if (![view isKindOfClass:[UIImageView class]]) {
                    [view removeFromSuperview];
                }
            }
        }
    }

    
    // 切换的View隐藏时-慢慢向下拉-拉到最底部时-切换的View显示
    if (currentContentOffset == -99) {
        [[NSNotificationCenter defaultCenter]postNotificationName:KDISPLAYHIDEDYNAMICUIVIEW object:@"display"];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    // 此处判断2G/3G、WiFi、网络连接失败
    if ( [IMB_NetUtils checkGPRSNet]) {
        NSLog(@"GPRS");
    }else if([IMB_NetUtils checkWifiNet]){
        NSLog(@"WiFi");
        if ([currentCell.fileFlg isEqualToString:@"1"]) {
            [currentCell playVideoAction:nil];
        }
    }else {
        NSLog(@"无网络连接");
    }
}

// 判断向上或向下滚动
float lastContentOffset;
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    lastContentOffset = scrollView.contentOffset.y;
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    
    if (currentContentOffset > 0) {
        if (lastContentOffset < scrollView.contentOffset.y) {
            // NSLog(@"向上滚动显示");
            [[NSNotificationCenter defaultCenter]postNotificationName:KDISPLAYHIDEDYNAMICUIVIEW object:@"hide"];
            
        }else{
            // NSLog(@"向下滚动隐藏");
            [[NSNotificationCenter defaultCenter]postNotificationName:KDISPLAYHIDEDYNAMICUIVIEW object:@"display"];
        }
    }
}

#pragma mark 列表的委托与dataSource

- (void)setExtraCellLineHidden:(UITableView *)tableView
{
    UIView *view = [UIView new];
    view.backgroundColor = APP_OBJECT_GRAY_COLOR;
    view.backgroundColor = [UIColor orangeColor];
    [tableView setTableFooterView:view];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self calcCellHeight:indexPath];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.netArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"BN_DynamicCell";
    BN_DynamicCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"BN_DynamicCell" owner:nil options:nil]objectAtIndex:0];
        cell.tag = indexPath.row;
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }
    
    for (UIView *view in cell.displayImageView.subviews) {
        [view removeFromSuperview];
    }
    
    for (UIView *view in cell.replView.subviews) {
        [view removeFromSuperview];
    }
    
    [cell toUpdateListData:^(BOOL isUpdate, NSInteger pageNumber) {
        if (isUpdate) {
            [self performSelectorInBackground:@selector(loadNetData) withObject:nil];
        }
    }];

    cell.netArray = self.netArray;
    cell.cellTag = indexPath.row;
    cell.infoArray = self.netArray;
    
    
    // 用户权限
    NSInteger postUserType = [self.netArray[indexPath.row][@"postUserType"] integerValue];
    [self dynamicUserType:cell.deleteDynamicBtn userType:postUserType];

    // 是否收藏
    cell.favoFlg = [self.netArray[indexPath.row][@"favoFlg"] integerValue];
    
    // postId
    cell.postId = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"postId"]];
    
    // 滑动最后一个CELL时 加载数据
    cell.userName.text = self.netArray[indexPath.row][@"postUserName"];
    
    NSString *dateStr = self.netArray[indexPath.row][@"postDate"];
    NSRange rang = NSMakeRange(10, 6);
    NSString * strRang = [dateStr substringWithRange:rang];
    cell.sendTime.text = strRang;
    
    // 赞
    cell.praiFlg = [self.netArray[indexPath.row][@"praiFlg"]intValue];
    cell.praiTime = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"praiTime"]];
    NSString *praiTime = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"praiTime"]];
    cell.likeLabel.backgroundColor = [UIColor clearColor];
    cell.likeLabel.text = praiTime;
    [cell dealLikeBtnColorState];
    
    // 浏览次数 browTime
    cell.lookTimes.text = nil;
    NSString *browTime = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"browTime"]];
    if (![browTime isEqual:[NSNull null]]) {
        
        cell.lookTimes.text = [NSString stringWithFormat:@"浏览%@次",browTime];
    }else {
        cell.lookTimes.text = @"浏览0次";
    }
    
    // 评论数量 replTime 居然是数值型....
    cell.replTime = [self.netArray[indexPath.row][@"replTime"] integerValue];
    NSString *replTime = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"replTime"]];
    if (![replTime isEqual:[NSNull null]]) {
        for (UILabel *view in cell.pingLunBtn.subviews) {
            if ([view isKindOfClass:[UILabel class]]) {
                [view removeFromSuperview];
            }
        }
        UILabel *pinlunLabel = [[UILabel alloc]init];
        
        switch (MAIN_VERSION) {
            case 7:
                pinlunLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+1, 50, 12);
                break;
            case 6:
                pinlunLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+2, 50, 12);
                break;
            default:
                break;
        }
        UIColor *color = APP_OBJECT_GREEN_COLOR;
        pinlunLabel.textColor = color;
        pinlunLabel.backgroundColor = [UIColor clearColor];
        pinlunLabel.font = [UIFont systemFontOfSize:12];
        pinlunLabel.text = replTime;
        [cell.pingLunBtn addSubview:pinlunLabel];
    }
    
    // fileFlg为0是图片 1为视频
    NSArray *files = self.netArray[indexPath.row][@"files"];
    NSString *fileFlg = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"fileFlg"]];
    cell.fileFlg = fileFlg;
    if ([fileFlg isEqualToString:@"0"]) {
        NSArray *files = self.netArray[indexPath.row][@"files"];
        [cell imgArray:files];
    }else {
        [cell video:files];
    }
    
    // 文字内容
    NSString *postSubj = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"postSubj"]];
    if (![postSubj isEqual:[NSNull null]]) {
        if (![postSubj isEqualToString:@"  写点什么呢..."]) {
            cell.contentText.text = postSubj;
        }
    }
    // 评论数
    [cell.contentText sizeToFit];
    [cell relayout];
    cell.replArr = self.netArray[indexPath.row][@"repls"];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark
#pragma mark Notification Action

- (void)autoRefreshClassTableView:(NSNotification *)notification {
    if (!self.dynamicHelper) {
        self.dynamicHelper = [[BN_DynamicHelper alloc]init];
    }
    [self loadNetData];
}

- (void)removeVideoView:(NSNotification *)notification {
    [currentCell removeMovieView];
}

- (void)reloadDataForTableView {
    [self loadNetData];
}


#pragma mark 封装自动撑开高度的方法
- (CGSize)getTextSize:(CGSize)provisionsSize disFont:(UIFont *)font contentStr:(NSString *)contentStr contextDic:(NSDictionary *)contextDic {
    
    CGSize size;
    switch (MAIN_VERSION) {
        case 7:
            size =[contentStr boundingRectWithSize:provisionsSize options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:contextDic context:nil].size;
            
            break;
            
        case 6:
            size = [contentStr sizeWithFont:font constrainedToSize:provisionsSize lineBreakMode:UILineBreakModeWordWrap];
            break;
        default:
            break;
    }
    return size;
}

#pragma mark dealloc
- (void)dealloc
{
    NSLog(@"动态_班级 Modal 释放");
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KDISPLAYHIDEDYNAMICUIVIEW object:nil];
    // KDYNAMIC_HINTMESSAGE
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KDYNAMIC_HINTMESSAGE object:nil];

    [_header free];
    [_footer free];
}

@end
